from fastapi import APIRouter, Depends, HTTPException, Query
from src.schemas.checkin import (
    CheckinStatusApiResponse,
    CheckinApiResponse,
    CheckinHistoryApiResponse,
    CheckinSummaryApiResponse,
    CheckinSummaryRequest
)
from src.schemas.response import ErrorResponse
from src.services.checkin_service import CheckinService
from src.utils.auth import get_current_user
from src.models.user import User
from src.utils.logger import app_logger as logger


router = APIRouter()


@router.get("/status", response_model=CheckinStatusApiResponse, summary="获取打卡状态")
async def get_checkin_status(
    current_user: User = Depends(get_current_user)
):
    """获取用户当前打卡状态"""
    try:
        result = await CheckinService.get_checkin_status(current_user.id)
        
        if result["success"]:
            return CheckinStatusApiResponse(
                code=200,
                message="获取打卡状态成功",
                data=result["data"]
            )
        else:
            raise HTTPException(status_code=400, detail=result["message"])
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取打卡状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取打卡状态失败: {str(e)}")


@router.post("/", response_model=CheckinApiResponse, summary="执行打卡")
async def perform_checkin(
    current_user: User = Depends(get_current_user)
):
    """执行打卡操作"""
    try:
        result = await CheckinService.perform_checkin(current_user.id)
        
        if result["success"]:
            return CheckinApiResponse(
                code=200,
                message=result["message"],
                data=result["data"]
            )
        else:
            # 只有真正的错误才返回400
            raise HTTPException(status_code=400, detail=result["message"])
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"打卡操作失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"打卡操作失败: {str(e)}")


@router.get("/history", response_model=CheckinHistoryApiResponse, summary="获取打卡历史")
async def get_checkin_history(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(10, ge=1, le=100, description="每页数量"),
    current_user: User = Depends(get_current_user)
):
    """获取用户打卡历史记录"""
    try:
        result = await CheckinService.get_checkin_history(current_user.id, page, limit)
        
        if result["success"]:
            return CheckinHistoryApiResponse(
                code=200,
                message="获取打卡历史成功",
                data=result["data"]
            )
        else:
            raise HTTPException(status_code=400, detail=result["message"])
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取打卡历史失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取打卡历史失败: {str(e)}")


@router.get("/summary", response_model=CheckinSummaryApiResponse, summary="获取打卡汇总")
async def get_checkin_summary(
    year: int = Query(..., ge=2020, le=2030, description="年份"),
    month: int = Query(..., ge=1, le=12, description="月份"),
    current_user: User = Depends(get_current_user)
):
    """获取用户指定年月的打卡汇总数据"""
    try:
        result = await CheckinService.get_checkin_summary(current_user.id, year, month)
        
        if result["success"]:
            return CheckinSummaryApiResponse(
                code=200,
                message="获取打卡汇总成功",
                data=result["data"]
            )
        else:
            raise HTTPException(status_code=400, detail=result["message"])
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取打卡汇总失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取打卡汇总失败: {str(e)}")